<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row :gutter="40">
        <el-col v-if="formFlag === true" :span="24">
          <el-form-item label="转派详情" prop="engineerCode">
            由二线工程师 {{ formItem.transferUserName }} 转派给 {{ loginName }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="故障级别" prop="faultLevel">
            <el-select v-model="formItem.faultLevel" placeholder="请选择故障级别">
              <el-option v-for="item in availableFailureLevels" :key="item.code" :label="item.text" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="参与工程师" prop="engineerCode">
            <el-select v-model="formItem.engineerCode" multiple filterable clearable placeholder="请选择参与工程师">
              <el-option v-for="(item) in users" :key="item.username" :label="item.name" :value="item.username" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="故障解决情况" prop="context">
            <el-input v-model="formItem.context" placeholder="请输入故障解决情况" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" resize="none" />
          </el-form-item>
        </el-col>
        <!-- 资产列表 -->
        <el-col :span="24">
          <div id="资产列表">
            <div class="anthor-info-head">
              <div>
                <el-row :gutter="40">
                  <el-col :span="12">
                    <i class="el-icon-document" agalin /><span>资产明细</span>
                  </el-col>
                  <el-col :span="12">
                    <div style="float:right">
                      <el-button type="primary" size="mini" icon="el-icon-plus" @click="showAsset = true">选择资产</el-button>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
            <div class="anthor-info-body" style="margin:10px">
              <el-table
                :loading="false"
                :data="formItem.assetObjs"
              >
                <el-table-column v-for="column in insideAssetColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
                  <template slot-scope="scope">
                    <column-render :render="column.render" :row="scope.row" :column="column" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button type="text" title="删除" size="mini" icon="el-icon-delete" @click.native.prevent="removeAssets(scope.$index)" />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-col>

        <!-- 备品备件列表 -->
        <el-col :span="24">
          <div id="备品备件列表">
            <div class="anthor-info-head">
              <div>
                <el-row :gutter="40">
                  <el-col :span="12">
                    <i class="el-icon-document" agalin /><span>备品备件明细</span>
                  </el-col>
                </el-row>
              </div>
            </div>
            <div class="anthor-info-body" style="margin:10px">
              <el-table
                :loading="false"
                :data="formItem.spareParts"
              >
                <el-table-column v-for="column in insideStockColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
                  <template slot-scope="scope">
                    <column-render :render="column.render" :row="scope.row" :column="column" />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-col>

        <el-col :span="24">
          <div style="float:right">
            <!-- <el-button size="mini" type="warning" @click="ok('temporary',false)">保存</el-button> -->
            <el-button size="mini" type="primary" @click="ok('submit',false)">提交</el-button>
            <el-button v-if="formFlag === false" size="mini" @click="dialogFormVisible = true">转派</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <!-- 资产 -->
    <SelectDialog title="选择资产" :append-to-body="true" :show="showAsset" @on-ok="selectAssetOk" @on-cancel="selectAssetCancel">
      <AssetTable v-if="showAsset" ref="assets" :init-query="{s_statusCode: 'using'}" :for-selection="true" />
    </SelectDialog>

    <FormDialog title="转其他二线工程师" :show="dialogFormVisible" width="30%" :append-to-body="true" @on-ok="tranferOk" @on-cancel="cancel">
      <el-form ref="dialogform" :model="formItem" :rules="rules" label-width="100px" size="mini">
        <el-row :gutter="40">
          <el-col :span="24">
            <el-form-item label="转派工程师" prop="transferEngineerCode">
              <el-select v-model="formItem.transferEngineerCode" filterable clearable placeholder="请选择转派工程师">
                <el-option v-for="(item) in users" :key="item.username" :label="item.name" :value="item.username" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="转派原因" prop="transferReason">
              <el-input v-model="formItem.transferReason" placeholder="请输入转派原因" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" resize="none" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </FormDialog>
  </div>
</template>

<script>
import FormDialog from '@neu/biz-core/components/FormDialog'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import AssetTable from '@neu/dcam-ui/views/fixedAsset/tables'

import { secondLineCreate as create, secondLineDetail as detail } from '@neu/dcom-ui/api/alter'
import { findByDictionaryType } from '@neu/dcom-ui/api/dictionary'
import { list as userList } from '@neu/auth-ui/api/user'
import { deepClone } from '@neu/biz-core/utils'

const formItem = {
  // 工作流TaskId
  taskId: '',
  // 工单号
  workNum: '',
  // 转派人
  transferUserName: '',
  // 故障级别
  faultLevel: '',
  // 参与工程师
  engineerCode: [],
  // 参与工程师
  engineerName: [],
  // 故障解决情况
  context: '',
  // 选择的资产
  assets: '',
  // 操作人名称
  operatorCode: '',
  // 操作人编码
  operatorName: '',
  // 是否转派 *
  transfer: false,
  // 转派工程师名称
  transferEngineerName: '',
  // 转派工程师编码
  transferEngineerCode: '',
  // 转派原因
  transferReason: '',
  // 资源集合
  assetObjs: [],
  // 备品备件
  spareParts: [],
  // 状态
  status: 'temporary'
}

const formRules = {
  context: [{ required: true, message: '故障解决情况不能为空', trigger: 'blur' }],
  transferEngineerCode: [{ required: true, message: '转派工程师不能为空', trigger: 'blur' }],
  transferReason: [{ required: true, message: '转派原因不能为空', trigger: 'blur' }]
}

export default {
  name: 'SecondLineHandleForm',
  components: {
    SelectDialog,
    AssetTable,
    FormDialog
  },
  props: {
    taskId: {
      required: false,
      type: String,
      default: 'NULL'
    },
    workOrderNum: {
      required: false,
      type: String,
      default: ''
    },
    formFlag: {
      required: false,
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 资产的表头
      insideAssetColumns: [
        { title: '资产分类', key: 'assetTypeName' },
        { title: '资产编号', key: 'code' },
        { title: '资产名称', key: 'name' },
        { title: '资产条码', key: 'sequence' },
        { title: '规格型号', key: 'productName' }
      ],
      // 资产的弹窗
      showAsset: false,
      // 备品备件的弹窗
      showStock: false,
      // 备品备件的表头
      insideStockColumns: [
        {
          title: '货品编号',
          key: 'storckNumber'
        }, {
          title: '备品备件分类',
          key: 'spareTypeName'
        },
        {
          title: '规格型号',
          key: 'specification'
        },
        {
          title: 'SN',
          key: 'sn'
        },
        {
          title: '存放库房',
          key: 'storehouseName'
        },
        {
          title: '单价',
          key: 'unitPrice'
        },
        {
          title: '货品来源',
          key: 'source',
          render: (h, params) => {
            let sourceDesc = ''
            if (params.row.source === 'new') {
              sourceDesc = '合同采购'
            } else if (params.row.source === 'back') {
              sourceDesc = '退库利旧'
            }
            return h('span', [
              h('el-tag', sourceDesc)
            ])
          }
        },
        {
          title: '关联合同',
          key: 'contractName'
        }
      ],
      // 参与工程师集合
      users: [],
      // 所有的故障级别
      availableFailureLevels: [],
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 当前登录人
      loginName: this.$store.getters.name,
      // 表单验证规则
      rules: { ...formRules },
      // 转派弹窗
      dialogFormVisible: false
    }
  },
  created() {
    this.fetch()

    // 故障级别
    findByDictionaryType('failureLevel').then(response => {
      this.availableFailureLevels = response.data
    })

    // 参与工程师集合
    userList({ 's_roleCode': 'expert' }).then(res => {
      this.users = res.data.map(e => {
        return { name: e.name, username: e.username }
      }).filter(item => item.name !== this.loginName)
    })
  },
  methods: {
    fetch() {
      if (this.workOrderNum !== 'NULL') {
        detail(this.workOrderNum, this.taskId).then(response => {
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    ok(value, transfer) {
      this.$refs.myform.validate((valid) => {
        if (valid) {
          // 赋值工单与任务id
          this.formItem.taskId = this.taskId
          this.formItem.workNum = this.workOrderNum

          if (transfer === false) {
            this.formItem.transferEngineerName = ''
            this.formItem.transferEngineerCode = ''
            this.formItem.transferReason = ''
          }

          const data = deepClone(this.formItem)
          // 是否转派
          data.transfer = transfer
          // 状态判断
          data.status = value

          // 参与人员
          const userCodes = this.formItem.engineerCode
          if (userCodes) {
            const filterData = this.users.filter(e => userCodes.indexOf(e.username) > -1)
            data.engineerName = filterData.map(e => e.name)
          } else {
            data.engineerName = []
          }

          create(data, (this.formFlag === false ? 'before' : 'after')).then(res => {
            if (res.status === 'success') {
              this.$emit('cancelNewOrderForm', 'refresh')
            }
          })
        }
      })
    },
    selectAssetOk() {
      const that = this
      const assets = this.$refs.assets.selections
      if (assets && assets.length > 0) {
        assets.forEach(e => {
          const one = that.formItem.assetObjs.find(k => k.code === e.code)
          if (!one) {
            that.formItem.assetObjs.push(e)
          }
        })
        this.showAsset = false
      } else {
        this.$message({
          showClose: true,
          message: '请选择资产',
          type: 'error'
        })
      }
    },
    // 关闭资产
    selectAssetCancel() {
      this.showAsset = false
    },
    // 移除资产
    removeAssets(index) {
      this.formItem.assetObjs.splice(index, 1)
    },
    selectStockOk() {
      const that = this
      const stocks = this.$refs.stocks.selections
      if (stocks && stocks.length > 0) {
        stocks.forEach(e => {
          const one = that.formItem.spareParts.find(k => k.spareId === e.id)
          if (!one) {
            that.formItem.spareParts.push({ spareId: e.id, num: 0, ...e })
          }
        })
        this.showStock = false
      } else {
        this.$message({
          showClose: true,
          message: '请选择备品备件',
          type: 'error'
        })
      }
    },
    // 关闭备品备件
    selectStockCancel() {
      this.showStock = false
    },
    // 移除备品备件
    removeStocks(index) {
      this.formItem.spareParts.splice(index, 1)
    },
    // 转派弹窗确认
    tranferOk() {
      if (!this.formItem.engineerCode) {
        this.$message({
          showClose: true,
          message: '请选择转派工程师',
          type: 'error'
        })
        return false
      }

      if (!this.formItem.transferReason) {
        this.$message({
          showClose: true,
          message: '请填写转派原因',
          type: 'error'
        })
        return false
      }

      // 转派工程师名称
      const one = this.users.find(e => e.username === this.formItem.transferEngineerCode)
      this.formItem.transferEngineerName = one ? one.name : ''
      // 提交后台
      this.ok('submit', true)
    },
    // 弹窗取消
    cancel() {
      this.dialogFormVisible = false
    }
  }
}
</script>
